﻿using AutoMapper;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.EMMA;
using Domain.Examin;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.ApprovalProcess;
using ReturnValue;
using System.Diagnostics;
using System.Transactions;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Handler.ApprovalProcess
{
    public class ConfigurationNodeHandler : IRequestHandler<ConfigurationNodeCommand, ApiResult<int>>
    {
        private readonly IRepository<ApprovalNodeModel> approvalNodeRepo;
        private readonly IMapper mapper;
        private readonly ILogger<ConfigurationNodeHandler> logger;
        private readonly IRepository<approvalProcessInstanceModel> approvalProcessRepo;

        public ConfigurationNodeHandler(
            IRepository<ApprovalNodeModel> approvalNodeRepo,
            IMapper mapper,
            ILogger<ConfigurationNodeHandler> logger,
            IRepository<approvalProcessInstanceModel> approvalProcessRepo
            )
        {
            this.approvalNodeRepo = approvalNodeRepo;
            this.mapper = mapper;
            this.logger = logger;
            this.approvalProcessRepo = approvalProcessRepo;
        }
        public async Task<ApiResult<int>> Handle(ConfigurationNodeCommand request, CancellationToken cancellationToken)
        {
            //删除所有节点
            var entityes = approvalNodeRepo.GetAll().Where(x => x.processId == request.processId).ToList();
            foreach (var entity in entityes)
            {
                entity.IsDel = true;
            }

            //批量添加节点
            var models = mapper.Map<List<ApprovalNodeModel>>(request.createFromFieIdDtos);
            foreach (var model in models)
            {
                model.Id = YitIdHelper.NextId();
            }
            approvalProcessInstanceModel process = new approvalProcessInstanceModel()
            {
                Id= YitIdHelper.NextId(),
                processId= models[0].Id,
                currentNodeId= models[0].Id,
                productionOrder = models[0].prevnodeId??'0',
                initiator=0,
                status=0,
                starttiome=DateTime.Now,
                endtime=DateTime.Now
            };
            int r0 = 0;
            int r1 = 0;
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    r0 = await approvalNodeRepo.UpdateRangeAsync(entityes);
                    r1 = await approvalNodeRepo.CreateRangeAsync(models);
                    await approvalProcessRepo.AddAsync(process);
                    tran.Complete();//提交分布式事务
                }
                catch (Exception ex)
                {
                    logger.LogError($"事务中添加流程节点配置失败已回滚:{ex.Message}");
                    throw;
                }
            }
            if (r1 > 0)
            {
                return new ApiResult<int>().AddSuccess("流程节点配置", r1);
            }
            else
            {
                return new ApiResult<int>().AddFail("流程节点配置");
            }
        }
    }
}
